package org.fuxian.util;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.fuxian.model.vo.Location;
import java.util.ArrayList;
import java.util.List;

/**
 * 百度地图工具类
 */
public class BaiduMapUtil {

    /**
     * 根据地址获取经纬度
     * location[0] lat 维度
     * lcation[1] lng 经度
     *
     * @param address
     * @return
     */
    public static Location getLocation(String address) {
        String url = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=PDWIlCwy6m2PvyTKNS098Qih0u7DWGEX";
        String jsonStr = HttpUtil.get(url);
        Location location = null;
        // lat 纬度值
        //lng 经度值
        JSONObject obj = JSONUtil.parseObj(jsonStr);
        int status = obj.getInt("status");
        if (status == 0) {
            JSONObject resultObj = obj.getJSONObject("result");
            JSONObject locationObj = resultObj.getJSONObject("location");
            location = new Location(locationObj.getStr("lng"), locationObj.getStr("lat"));
        }
        return location;
    }

    /**
     * 根据起点和终点坐标获取路线经纬度json字符串
     * @return
     */
    public static String getPathJsonStrByLocation(Location startPoint, Location endPoint) {
        String url = "https://api.map.baidu.com/directionlite/v1/driving?origin=" + startPoint.getLat() + "," + startPoint.getLng() + "&destination=" + endPoint.getLat() + "," + endPoint.getLng() + "&ak=PDWIlCwy6m2PvyTKNS098Qih0u7DWGEX";
        String jsonStr = HttpUtil.get(url);
        JSONObject obj = JSONUtil.parseObj(jsonStr);
        JSONObject resultObj = obj.getJSONObject("result");
        JSONArray array = resultObj.getJSONArray("routes");
        JSONObject routeObj = (JSONObject) array.get(0);
        JSONArray steps = routeObj.getJSONArray("steps");
        ArrayList<Location> locations = new ArrayList<>();

        for (int i = 0; i < steps.size(); i++) {
            JSONObject stepObj = (JSONObject) steps.get(i);
            locations.addAll(getLocationByStr(stepObj.getStr("path")));
        }
        return JSONUtil.toJsonStr(locations);
    }

    private static ArrayList<Location> getLocationByStr(String locationStr) {
        ArrayList<Location> locations = new ArrayList<>();
        List<String> points = StrUtil.splitTrim(locationStr, ";");
        for (String str : points) {
            List<String> pointStr = StrUtil.splitTrim(str, ",");
            Location location = new Location(pointStr.get(0), pointStr.get(1));
            locations.add(location);
        }
        return locations;
    }


    public static void main(String[] args) {
//        getLocation("河南工业职业技术学院");

        System.out.println(getPathJsonStrByLocation(getLocation("河南省南阳市农业职业学院"),
                getLocation("南阳电视台南阳广电中心")));

    }


}
